<?php

namespace app\admin\controller;

use app\model\OrderModel;
use app\model\OrderItemModel;
use app\model\UserModel;
use app\model\PickUpPointModel;
use support\Request;
use support\Response;
use Exception;
use app\model\Util;

class OrderController
{

    public function orderStatusData(Request $request)
    {
        //0待付款，1已付款，2已发货，3已完成，4已取消，5已退款
        $statusList = [
            0 => '待付款',
            1 => '已付款',
            2 => '已发货',
            3 => '已完成',
            4 => '已取消',
            5 => '已退款',
        ];

        $data = [];
        foreach ($statusList as $key => $value) {
            $num = OrderModel::where('status', '=', $key)
                ->where('express_type', '=', 'express')->count();

            $data[] = [
                'status' => $key,
                'name' => $value,
                'num' => $num
            ];
        }

        $status2List = [
            0 => '待付款',
            1 => '已付款',
            2 => '待提货',
            3 => '已完成',
            4 => '已取消',
            5 => '已退款',
        ];
        $data2 = [];
        foreach ($status2List as $key => $value) {
            $num = OrderModel::where('status', '=', $key)
                ->where('express_type', '=', 'pickUpPoint')->count();
            $data2[] = [
                'status' => $key,
                'name' => $value,
                'num' => $num
            ];
        }

        return json([
            'data' => [
                'statusList' => $data,
                'status2List' => $data2,
            ],
            'msg' => '获取成功',
            'code' => 20000
        ]);
    }

    /**
     * 获取订单列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $status = $request->get('status');
            $pay_status = $request->get('pay_status');
            $express_type = $request->get('express_type');
            $keyword = $request->get('keyword');
            $startDate = $request->get('startDate');
            $endDate = $request->get('endDate');

            $query = OrderModel::query()
                ->with(['user', 'pick_up_point', 'items'])
                ->orderBy('id', 'desc');

            // 状态筛选
            if ($status !== null && $status !== '') {
                $query->where('status', $status);
            }

            // 支付状态筛选
            if ($pay_status !== null && $pay_status !== '') {
                $query->where('pay_status', $pay_status);
            }

            // 配送方式筛选
            if ($express_type !== null && $express_type !== '') {
                $query->where('express_type', $express_type);
            }

            // 关键词搜索
            if ($keyword) {
                $query->where(function ($q) use ($keyword) {
                    $q->where('order_no', 'like', "%{$keyword}%")
                        ->orWhere('receiver_name', 'like', "%{$keyword}%")
                        ->orWhere('receiver_phone', 'like', "%{$keyword}%")
                        ->orWhere('sender_phone', 'like', "%{$keyword}%");
                });
            }

            if(!empty($startDate)){
                $query->where('pay_time', '>=', strtotime($startDate));
            }
            if(!empty($endDate)){
                $query->where('pay_time', '<', strtotime($endDate) + 86400);
            }

            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['updated_at'] = date('Y-m-d H:i:s', $item->updated_at);
                if ($item->pay_time) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item->pay_time);
                }
                if ($item->delivery_time) {
                    $item['delivery_time'] = date('Y-m-d H:i:s', $item->delivery_time);
                }
                if ($item->refund_at) {
                    $item['refund_at'] = date('Y-m-d H:i:s', $item->refund_at);
                }
                if ($item->pay_expired_at) {
                    $item['pay_expired_at'] = date('Y-m-d H:i:s', $item->pay_expired_at);
                }

                // 格式化状态文本
                $item['status_text'] = $item->getStatusText();
                $item['pay_status_text'] = $this->getPayStatusText($item->pay_status);
                $item['delivery_status_text'] = $this->getDeliveryStatusText($item->delivery_status);
                $item['refund_status_text'] = $this->getRefundStatusText($item->refund_status);

                // 格式化支付方式
                $item['pay_method_text'] = $this->getPayMethodText($item->pay_method);

                // 格式化配送方式
                $item['express_type_text'] = $this->getExpressTypeText($item->express_type);
                if($item->express_send_user_id > 0){
                    $sender = UserModel::find($item->express_send_user_id);
                    $item['express_send_user_name'] = $sender ? $sender->nickname : '';
                }

                
            }

            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取订单详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $id = (int)$request->get('id');

            $order = OrderModel::with(['user', 'pick_up_point', 'items'])
                ->find($id);

            if (!$order) {
                return json([
                    'data' => null,
                    'msg' => '订单不存在',
                    'code' => 0
                ]);
            }

            // 格式化时间
            $order['created_at'] = date('Y-m-d H:i:s', $order->created_at);
            $order['updated_at'] = date('Y-m-d H:i:s', $order->updated_at);
            if ($order->pay_time) {
                $order['pay_time'] = date('Y-m-d H:i:s', $order->pay_time);
            }
            if ($order->delivery_time) {
                $order['delivery_time'] = date('Y-m-d H:i:s', $order->delivery_time);
            }
            if ($order->refund_at) {
                $order['refund_at'] = date('Y-m-d H:i:s', $order->refund_at);
            }
            if ($order->pay_expired_at) {
                $order['pay_expired_at'] = date('Y-m-d H:i:s', $order->pay_expired_at);
            }

            return json([
                'data' => $order,
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新订单状态
     * @param Request $request
     * @return Response
     */
    public function updateStatus(Request $request): Response
    {
        try {
            $id = (int)$request->post('id');
            $status = (int)$request->post('status');

            $order = OrderModel::find($id);
            if (!$order) {
                return json([
                    'data' => null,
                    'msg' => '订单不存在',
                    'code' => 0
                ]);
            }

            $order->status = $status;

            if($status == 1){
                // 设置已付款需要同步pay_status
                $order->pay_status = 1;
            }

            $order->updated_at = time();
            $order->save();

            return json([
                'data' => null,
                'msg' => '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取支付状态文本
     */
    private function getPayStatusText($status): string
    {
        $texts = [
            0 => '未支付',
            1 => '已支付',
            2 => '已退款'
        ];
        return $texts[$status] ?? '未知';
    }

    /**
     * 获取发货状态文本
     */
    private function getDeliveryStatusText($status): string
    {
        $texts = [
            0 => '未发货',
            1 => '已发货',
            2 => '已签收'
        ];
        return $texts[$status] ?? '未知';
    }

    /**
     * 获取退款状态文本
     */
    private function getRefundStatusText($status): string
    {
        $texts = [
            0 => '未退款',
            1 => '退款中',
            2 => '已退款'
        ];
        return $texts[$status] ?? '未知';
    }

    /**
     * 获取支付方式文本
     */
    private function getPayMethodText($method): string
    {
        $texts = [
            'wechat' => '微信支付',
            'alipay' => '支付宝',
            'score' => '云豆支付'
        ];
        return $texts[$method] ?? '未知';
    }

    /**
     * 获取配送方式文本
     */
    private function getExpressTypeText($type): string
    {
        $texts = [
            'pickUpPoint' => '自提点',
            'express' => '快递配送'
        ];
        return $texts[$type] ?? '未知';
    }
}
